#include "msgQueue.h"
#include "bank.h"
#include "tools.h"

//通信消息
ClientToServe ctos;
ServeToClient stoc;

//消息队列ID
int stocMsgId = 0;
int ctosMsgId = 0;

void take(void)
{
	char path[PATH_LEN] = {};
	sprintf(path,"%s%s",ACC_PATH,ctos.acc.bank);

	int fd = open(path,O_RDWR);
	if(0 > fd)
	{
		error("open");
		sprintf(stoc.info,"N:服务器正在升级，取款失败!");
		return;
	}

	Acc acc = {};
	read(fd,&acc,sizeof(Acc));

	if(acc.balance < ctos.acc.balance)
	{
		sprintf(stoc.info,"N:余额不足，取款失败！当前余额为:%g",acc.balance);
		return;
	}

	acc.balance -= ctos.acc.balance;
	lseek(fd,0,SEEK_SET);
	write(fd,&acc,sizeof(Acc));
	close(fd);

	sprintf(stoc.info,"Y:取款成功，当前余额为:%g",acc.balance);
}

int main()
{
	//获取两个消息队列
	stocMsgId = getMsg(STOC_KEY);
	ctosMsgId = getMsg(CTOS_KEY);

	while(true)
	{
		ctos.type = M_TAKE;
		receiveMsg(ctosMsgId,&ctos,sizeof(ctos));

		take();

		stoc.type = ctos.pid;
		sendMsg(stocMsgId,&stoc,sizeof(stoc));
	}
}
